package com.juli.school.service.impl;

import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.juli.school.dao.entity.Fav;
import com.juli.school.dao.mapper.FavMapper;
import com.juli.school.service.bo.FavBo;
import com.juli.school.utils.core.model.CommonResp;
import com.juli.school.utils.core.model.PageResp;
import com.juli.school.utils.dao.base.Page;
import com.juli.school.utils.self.BeanUtilEx;

@Service
public class FavService {
	
	private static final Logger logger = LoggerFactory.getLogger(FavService.class);
	
	@Resource
	FavMapper favMapper;
	
	public CommonResp<String> add(FavBo favBo) {
		CommonResp<String> commonResp = new CommonResp<String>();
		if(Strings.isNullOrEmpty(favBo.getSnStamp())) {
			commonResp.fail("发布编号不可为空");
			return commonResp;
		}
		if(favBo.getFavKind() == null) {
			commonResp.fail("发布类型不可为空");
			return commonResp;
		}
		if(favBo.getStuId() == null) {
			commonResp.fail("学生ID不可为空");
			return commonResp;
		}
		try {
			favBo.setRecTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
			if(favMapper.get(favBo) == null) {
				favMapper.insert(favBo);
			}
			commonResp.success();
			logger.info("新增编号【{}】的收藏点赞信息成功",favBo.getSnStamp());
		} catch (Exception e) {
			logger.error("收藏/点赞系统异常",e);
			commonResp.exception();
		}
		return commonResp;
	}

	public CommonResp<Boolean> delete(FavBo favBo) {
		CommonResp<Boolean> commonResp = new CommonResp<Boolean>();
		if(Strings.isNullOrEmpty(favBo.getSnStamp())) {
			commonResp.fail("发布编号不可为空");
			return commonResp;
		}
		if(favBo.getFavKind() == null) {
			commonResp.fail("发布类型不可为空");
			return commonResp;
		}
		if(favBo.getStuId() == null) {
			commonResp.fail("学生ID不可为空");
			return commonResp;
		}
		try {
			favMapper.delete(favBo);
			commonResp.success();
			logger.info("删除编号【{}】的收藏点赞信息成功",favBo.getSnStamp());
		} catch (Exception e) {
			logger.error("取消收藏/点赞系统异常",e);
			commonResp.exception();
		}
		return commonResp;
	}
	
	public CommonResp<PageResp<FavBo>> listPage(FavBo favBo) {
		CommonResp<PageResp<FavBo>> commonResp = new CommonResp<PageResp<FavBo>>();
		Page page = new Page();
		page.setCurrentPage(favBo.getPageNo());
		page.setShowCount(favBo.getPageSize());
		favBo.setPage(page);
		try {
			List<Fav> listPage = favMapper.listPage(favBo);
			List<FavBo> list = Lists.newArrayList();
			for(Fav fav : listPage) {
				FavBo favBo2 = new FavBo();
				BeanUtilEx.copyProperties(favBo2, fav);
				list.add(favBo2);
			}
			commonResp.setData(new PageResp<FavBo>(list,favBo.getPage()));
		} catch (Exception e) {
			logger.error("分页获取所有收藏列表发生异常",e);
		}
		return commonResp;
	}
	
}
